<?php

namespace App\Models;

use App\Jobs\ClearMemberDataJob;
use App\Jobs\UserInit;
use App\Notifications\Overwrite\Notifiable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;
use DateTimeInterface;

class Member extends Authenticatable
{
    use HasFactory, HasApiTokens, Notifiable;

    protected $guarded = [];

    protected $hidden = [
        'openid',
        'password'
    ];

    public static function boot()
    {
        parent::boot();
        static::creating(function (Member $model) {
            if (!$model->account) {
                // 小程序上自动生成账号和密码
                $model->account =  uniqid();
                $model->password = bcrypt(123456);
            }
        });

        static::created(function (Member $model) {
            UserInit::dispatchSync($model->id);
        });

        static::deleting(function (Member $model) {
            ClearMemberDataJob::dispatch($model->id);
        });
    }

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function cashbooks()
    {
        return $this->belongsToMany(Cashbook::class, 'user_cashbooks', 'user_id', 'cashbook_id');
    }

    public function defaultCashbook()
    {
        return $this->hasOne(Cashbook::class, 'id', 'default_cashbook_id');
    }
}
